<template>
  <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
    <h3 class="title1">{{ title }}</h3>
    <el-form-item prop="phone">
      <el-input class="inputs" v-model="loginForm.phone" type="text" auto-complete="off" placeholder="手机号">
        <svg-icon slot="prefix" icon-class="phone" class="el-input__icon input-icon"/>
      </el-input>
    </el-form-item>
    <el-form-item prop="code">
      <el-input class="inputs"
        v-model="loginForm.code"
        auto-complete="off"
        placeholder="验证码"
        style="width: 70%"
      >
        <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon"/>
      </el-input>
      <div class="login-code" style="width: 25%">
        <el-button type="primary" style="width: 100%" @click="sendPhoneCode" :disabled="counting">
          <countdown v-if="counting" :time="60000" :interval="100" tag="span" @end="counting = false">
            <template slot-scope="props">
              - {{ props.seconds }} -
            </template>
          </countdown>
          <span v-else>发送</span>
        </el-button>
      </div>
    </el-form-item>
    <el-form-item prop="selectedUserName" v-if="selUsers.length>1" label="选择用户">
      <el-radio-group v-model="loginForm.username">
        <el-radio :label="u.userName" v-for="u in selUsers" :key="u.userId">{{ u.nickName }}</el-radio>
      </el-radio-group>
    </el-form-item>
    <Verify
      @success="captchaCheckSuccess"
      :mode="'pop'"
      :captchaType="captchaType"
      :imgSize="{ width: '330px', height: '155px' }"
      ref="verify"
    ></Verify>

    <el-form-item style="width:100%;">
      <el-button class="logins"
        :loading="loading"
        size="medium"
        type="primary"
        style="width:100%;"
        @click="handleLogin"
      >
        <span v-if="!loading">手 机 验 证 码 登 录</span>
        <span v-else>登 录 中...</span>
      </el-button>
      <div style="float: right;" v-if="register">
        <router-link class="link-type" :to="'/register'">立即注册</router-link>
      </div>
    </el-form-item>
    <!--插入-->
    <slot/>
  </el-form>
</template>

<script>
import {getCodeImg, getCaptchaType, getPhoneCaptcha, wechatCaptcha} from "@/api/login";
import {listUsersByPhone, listWechatUsersByPhone} from "@/api/system/user";
import Cookies from "js-cookie";
import {encrypt, decrypt} from '@/utils/jsencrypt'
import Verify from "@/components/Verifition/Verify";
import countdown from '@chenfengyuan/vue-countdown';

export default {
  name: "LoginFormPhoneCode",
  components: {Verify, countdown},
  data() {
    return {
      // title: process.env.VUE_APP_TITLE || '[[数研脚手架]]系统',
      title:'欢迎登录',
      captchaType: 'math',
      isImgCaptcha: true,
      isSlideValid: false,
      codeUrl: "",
      cookiePassword: "",
      loginForm: {
        username: "",
        phone: '',
        code: "",
        uuid: "",

        loginType: 'phoneCode'
      },
      loginRules: {
        phone: [
          {required: true, trigger: "blur", message: "手机号不能为空"},
          {pattern: /^1[34578]\d{9}$/, message: '请输入正确的手机号', trigger: "blur"}
        ],
        code: [{required: true, trigger: "change", message: "请输入验证码"}]
      },
      loading: false,
      // 验证码开关
      captchaOnOff: true,
      // 注册开关
      register: false,
      redirect: undefined,
      //验证码倒计时开关
      counting: false,
      selUsers: [],
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  async mounted() {
    this.getCookie();
    //验证码类型
    this.captchaType = (await getCaptchaType()).msg;
    this.isImgCaptcha = false;
    this.isSlideValid = false;
  },
  methods: {
    getCookie() {
      const phone = Cookies.get("phone");
      this.loginForm.phone = phone === undefined ? this.loginForm.phone : phone;
    },
    showValidCaptcha() {
      let captchaType = this.captchaType;

      if (captchaType == 'blockPuzzle' || captchaType == 'clickWord') {
        this.$refs.verify.show();
      } else {
        this.captchaCheckSuccess();
      }
    },

    captchaCheckSuccess() {
      //手机号登录============
      //启动倒计时
      this.counting = true;
      //发送验证码
      getPhoneCaptcha(this.loginForm.phone)
        .then(res => {
          this.loginForm.uuid = res.uuid;
        })
        .then(() => {
          //获取用户列表
          listUsersByPhone(this.loginForm.phone).then(res => {
            this.selUsers = res.data;
            if (this.selUsers.length) {
              this.loginForm.username = this.selUsers[0].userName;
            } else {
              this.loginForm.username = '';
            }
          })
        })
    },
    //发送验证码
    sendPhoneCode() {
      //校验手机号
      this.$refs.loginForm.validateField('phone', errorMsg => {
        if (errorMsg) {
          this.$modal.msgError(errorMsg);
        } else {
          //打开校验
          this.showValidCaptcha()
        }
      })
    },
    handleLogin() {

      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          Cookies.set("phone", this.loginForm.phone, {expires: 30});

          //执行登录
          this.$store.dispatch("Login", this.loginForm).then(() => {
            localStorage.setItem('weekPwd', '0');
            this.$router.push({path: this.redirect || "/"}).catch(() => {
            });
          }).catch(() => {
            this.loading = false;
          });
        } else {
          alert(JSON.stringify(this.loginForm))
        }
      });
    }
  }
};
</script>
